package com.suyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suyu.annotation.AuthCheck;
import com.suyu.common.BaseResponse;
import com.suyu.common.ErrorCode;
import com.suyu.common.ResultUtils;
import com.suyu.constant.UserConstant;
import com.suyu.exception.BusinessException;
import com.suyu.model.dto.user.DeleteRequest;
import com.suyu.model.entity.User;
import com.suyu.model.vo.LoginUserVO;
import com.suyu.service.UserService;
import com.suyu.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author tmh
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-09-13 12:55:06
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return
     */
    @Override
    @Transactional
    public BaseResponse userRegister(String userAccount, String userPassword, String checkPassword) {
        List<String> list = new ArrayList<>();
        Random random = new Random();
        list.add("她脸上的不是汗水而是玫瑰花的露水");
        list.add("求你不要再用脸蛋来杀人了，我已经厌倦了在你面前反复去世");
        list.add("你穿着绿色的雨衣，像一个药瓶子，里面是医我的药");
        list.add("不管有多少黑暗，也不管有多少转弯，用最初的心陪你走最远的路");
        list.add("今日份的美貌（帅气）也正常营业了");
        //1.校验参数是否未空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        //2.校验参数长度
        if (userAccount.length() < 4 || userPassword.length() < 4 || checkPassword.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数过短");
        }
        //3.校验用户名密码是否相等
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
        }
        //4.在同一个时刻不能够有两个一样的账户进行注册
        synchronized (userAccount.intern()) {


            //4.1数据库里面进行查询，确保用户名在数据库里面不存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            Long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            //4.2进行加密
            String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.SALT + userPassword).getBytes());
            //4.3插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setUserAvatar(UserConstant.DEFAULT_URL);
            user.setUserProfile(list.get(random.nextInt(list.size())));
            boolean save = save(user);
            if (!save) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            user.setUserPassword(null);
            return ResultUtils.success(user);
        }

    }


    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
//     * @param request      请求对象
     * @return
     */
    @Override
    public BaseResponse<LoginUserVO> userLogin(String userAccount, String userPassword/*,String captcha*/, HttpServletRequest request) {
 /*       //0.校验验证码是否满足要求
        String uuid = (String) request.getSession().getAttribute("uuid");
        String captchaCode = redisTemplate.opsForValue().get(uuid);
        //0.1 判断验证码是否失效
        if(captchaCode==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码失效");
        }
        //0.2 判断用户输入的验证码是否正确
        if (!captcha.equals(captchaCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码错误");
        }*/

        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //2.校验参数长度
        if (userAccount.length() < 4 || userPassword.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登录信息出错");
        }
        //3.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.SALT + userPassword).getBytes());
        //4.查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("user login failed , userAccount can not match the userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或者密码错误");
        }
        //5.记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        //得到安全的用户
        LoginUserVO loginUserVO = getLoginUserVo(user);

        //删除redis里面存放的键
//        redisTemplate.delete(uuid);

        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        //移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return ResultUtils.success();
    }

    /**
     * 获取用户信息
     *
     * @param request 请求对象
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (loginUser == null || loginUser.getId() == null) {
            return null;
        }
        long userId = loginUser.getId();
        return getById(userId);
    }

    /**
     * 获取脱敏的已经登录的用户信息
     *
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVo(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

}




